<template>
  <div class="table-box card">
    <div class="ed-head">
      <span class="title">{{ documentStatus === "edit" ? "修改" : documentStatus === "add" ? "新增" : "" }}退货订单</span>
      <el-icon class="pointer" @click="router.go(-1)"><CloseBold /></el-icon>
    </div>
    <el-form :model="purchaseForm" label-width="120px" :rules="couponRules" ref="ruleFormRef" :inline="true">
      <el-form-item label="供应商" prop="supplierId">
        <el-input class="width240" v-model="purchaseForm.supplierName" disabled>
          <template #append>
            <el-button type="primary" :icon="MoreFilled" @click="openRadioTreeTable('选择供应商', 0)" />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="退货原因" prop="returnType">
        <el-select class="width240" v-model="purchaseForm.returnType">
          <el-option v-for="unit in returnType" :label="unit.label" :value="unit.value" :key="unit.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="退货人" prop="contacts">
        <el-input class="width240" v-model="purchaseForm.contacts" />
      </el-form-item>
      <el-form-item label="退货日期" prop="date">
        <el-date-picker class="width240" v-model="purchaseForm.date" type="date" />
      </el-form-item>
      <el-form-item label="退货电话" prop="mobile">
        <el-input class="width240" v-model="purchaseForm.mobile" />
      </el-form-item>
      <el-form-item label="退货地址" prop="address">
        <el-input class="width240" v-model="purchaseForm.address" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input class="width240" v-model="purchaseForm.remark" placeholder="请填写" :rows="1" type="textarea" />
      </el-form-item>
    </el-form>
    <ProTable
      ref="proTable"
      row-key="id"
      :columns="columns"
      :data="purchaseForm.stockindetailList"
      :pagination="false"
      :is-card="false"
      show-summary
      :summary-method="getSummaries"
      :tool-button="documentStatus !== 'audited'"
    >
      <template #tableHeader>
        <el-button v-if="documentStatus !== 'audited'" type="primary" @click="openSelectTreeTable('选择原料')">
          添加原料
        </el-button>
      </template>
      <template #toolButton>
        <el-button v-if="documentStatus !== 'audited'" @click="onCheckSubmit" type="primary"> 保存并审核 </el-button>
        <el-button v-if="documentStatus !== 'audited'" @click="onSubmit" type="primary"> 保存 </el-button>
        <el-button v-if="documentStatus !== 'audited'" @click="router.go(-1)"> 返回 </el-button>
      </template>

      <template #operate="scope">
        <div class="flx-justify-between" v-if="!purchaseForm.checkFlag">
          <el-icon size="18" color="#169D82" @click="add"><Plus /></el-icon>
          <el-icon @click="delSpecRow(scope.$index)" size="18" color="#f00"><Minus /></el-icon>
        </div>
      </template>
      <template #barcode="scope">
        <el-input
          class="w100"
          v-model="scope.row.barcode"
          @change="onSearchCode"
          :ref="'input' + String(scope.$index) + String(1)"
          :disabled="documentStatus === 'audited'"
          @keyup.enter="handleKeyup($event, scope.$index, 1, scope.row.isGift)"
        >
          <template #append>
            <el-button
              type="primary"
              :icon="MoreFilled"
              @click="openSelectTreeTable('选择原料')"
              :disabled="documentStatus === 'audited'"
            />
          </template>
        </el-input>
      </template>

      <template #houseId="{ row }">
        <el-select v-model="row.houseId">
          <el-option v-for="item in houserList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </template>

      <template #quantity="scope">
        <el-input-number
          class="w100"
          v-model="scope.row.quantity"
          :controls="false"
          :precision="2"
          :min="0"
          :disabled="documentStatus === 'audited' || scope.row.isGift"
          @change="onChangeAmo(scope.$index)"
          :ref="'input' + String(scope.$index) + String(2)"
          @focus="event => event.target.select()"
          @keyup.enter="handleKeyup($event, scope.$index, 2, scope.row.isGift)"
        />
      </template>
      <template #price="scope">
        <el-input-number
          class="w100"
          :controls="false"
          :precision="2"
          v-model="scope.row.price"
          :disabled="documentStatus === 'audited' || scope.row.isGift"
          @change="onChangeAmo(scope.$index)"
          :ref="'input' + String(scope.$index) + String(3)"
          @focus="event => event.target.select()"
          @keyup.enter="handleKeyup($event, scope.$index, 3, scope.row.isGift)"
        />
      </template>
      <template #taxRate="scope">
        <el-input-number
          class="w100"
          :precision="2"
          :controls="false"
          v-model="scope.row.taxRate"
          :disabled="documentStatus === 'audited'"
          :ref="'input' + String(scope.$index) + String(4)"
          @focus="event => event.target.select()"
          @keyup.enter="handleKeyup($event, scope.$index, 4, scope.row.isGift)"
        />
      </template>
      <template #isGift="scope">
        <el-switch v-model="scope.row.isGift" :disabled="documentStatus === 'audited'" />
      </template>
      <template #giftQuantity="scope">
        <el-input-number
          :precision="2"
          class="w100"
          :controls="false"
          v-model="scope.row.giftQuantity"
          :disabled="documentStatus === 'audited' || !scope.row.isGift"
          :ref="'input' + String(scope.$index) + String(5)"
          @focus="event => event.target.select()"
          @keyup.enter="handleKeyup($event, scope.$index, 5, scope.row.isGift)"
        />
      </template>
    </ProTable>
    <SelectTreeTable @selected-list="handleSelectedTreeList" ref="selectTreeTableRef" />
    <SelectTreeTable @radio="onRadio" ref="radioTreeTableRef" />
  </div>
</template>
<script setup lang="ts" name="rejectionEdit">
import { ref, reactive, onMounted, getCurrentInstance, nextTick } from "vue";
import { useRouter, useRoute } from "vue-router";
import SelectTreeTable from "@/components/SelectTreeData/index.vue";
import {
  createStockin,
  editStockin,
  getStockin,
  getSupplierList,
  getWaresCategoryList,
  getWaresList,
  getSupplierRegionList,
  getStorehouseList,
  confirmStockin
} from "@/api/modules/inventory";
import ProTable from "@/components/ProTable/index.vue";
import { MoreFilled } from "@element-plus/icons-vue";
import type { FormInstance } from "element-plus";
import { replaceArrayItems } from "@/utils";
import { returnType } from "@/utils/serviceDict";
import { useUserStore } from "@/stores/modules/user.ts";
import { ElMessage } from "element-plus";
// 获取用户信息用于默认值
const { userInfo } = useUserStore();

const router = useRouter();
const route = useRoute();
const ruleFormRef = ref<FormInstance>();
const documentStatus = ref("add");
// 退货人退货电话 退货地址是登录账号人默认信息，登录时存入Vuex中取出使用
const purchaseForm = reactive({
  id: 0,
  orderType: -1,
  contacts: "",
  mobile: "",
  address: "",
  supplierId: "",
  date: "",
  status: 1,
  checkFlag: false,
  returnType: 1,
  remark: "",
  sourceId: "",
  printStatus: 0,
  stockindetailList: []
});
// 路由规则
const couponRules = reactive({
  // orderNo: [{ required: true, message: "请填写订单编号" }],
  // stockindetailList: [
  //   {
  //     validator: (rule, value, callback) => {
  //       console.log(value);
  //       if (value.length < 1) {
  //         callback(new Error("请选择原料"));
  //       } else {
  //         callback();
  //       }
  //     }
  //   }
  // ]
});

const delSpecRow = (index: number) => {
  if (purchaseForm.stockindetailList.length <= 1) return ElMessage.error("至少保留一项原料");
  purchaseForm.stockindetailList.splice(index, 1);
};

const onRadio = (row: any) => {
  purchaseForm.supplierId = row.data.id;
  purchaseForm.supplierName = row.data.name;
};

const columns: ColumnProps<Inventory.ResPurchaseList>[] = [
  { type: "index", label: "序号", width: 60 },
  { prop: "operate", label: "操作", width: 80 },
  { prop: "barcode", label: "编码" },
  { prop: "goodsName", label: "名称" },
  { prop: "houseId", label: "仓库", width: 170 },
  { prop: "productName", label: "规格", width: 130 },
  { prop: "quantity", label: "退货数量", width: 130 },
  { prop: "unitName", label: "单位", width: 120 },
  {
    prop: "unitBasis",
    label: "基准单位数量",
    width: 130
  },
  { prop: "price", label: "退货单价", width: 130 },
  { prop: "amount", label: "金额", width: 100 }
  // { prop: "isGift", label: "是否赠品", minWidth: 120 },
  // { prop: "giftQuantity", label: "赠送数量", minWidth: 120 }
];

const radioTreeTableRef = ref<InstanceType<typeof SelectTreeTable> | null>(null);

const openRadioTreeTable = (title: string, ix: number) => {
  const params = {
    title,
    isView: false,
    index: ix,
    selType: "radio",
    columns: [
      { type: "radio", label: "#", width: 60 },
      { prop: "name", label: "供应商名称", align: "left" }
    ],
    idName: "supplierCode",
    treeApi: getSupplierRegionList,
    api: getSupplierList
  };
  radioTreeTableRef.value?.acceptParams(params);
};

const onSearchCode = (value: string | number) => {
  if (Object.entries(value).length !== 0) {
    openSelectTreeTable("选择原料", value);
  }
};

const handleSelectedTreeList = (val: any) => {
  if (val.list.length > 0) {
    let list = val.list.map(im => {
      return {
        goodsName: im.name,
        goodsId: im.id,
        products: im.productName,
        productsId: im.prodcutId,
        productName: im.productName,
        quantity: 1,
        barcode: im.barcode,
        price: im.purPrice,
        amount: im.purPrice,
        taxRate: 0,
        isGift: false,
        giftQuantity: 0,
        houseId: defaultHouserId.value,
        convert: im.convert,
        unitName: im.unitName,
        unitBasis: im.convert
      };
    });
    purchaseForm.stockindetailList = replaceArrayItems(list, purchaseForm.stockindetailList, "goodsId");
    // purchaseForm.stockindetailList = list;
  }
};

interface SummaryMethodProps<T = Inventory.ResPurchaseList> {
  columns: TableColumnCtx<T>[];
  data: T[];
}

const add = () => {
  purchaseForm.stockindetailList.push({
    goodsName: "",
    goodsId: 0,
    products: "",
    productsId: 0,
    productName: 0,
    quantity: 0,
    price: 0,
    amount: 0,
    taxRate: 0,
    isGift: false,
    giftQuantity: 0
  });
};

const getSummaries = (param: SummaryMethodProps) => {
  const { columns, data } = param;
  const props: string[] = ["quantity", "amount", "giftQuantity"];
  const sums: string[] = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    if (!props.includes(column.property)) {
      sums[index] = "";
      return;
    }

    let valuesToSum: number[] = [];
    data.forEach(item => {
      if (column.property === "quantity" && item.isGift) {
        return; // 如果isGift为true，则不统计quantity
      }
      if (column.property === "amount" && item.isGift) {
        return; // 如果isGift为true，则不统计amount
      }
      if (column.property === "giftQuantity" && !item.isGift) {
        return; // 如果isGift为false，则不统计giftQuantity
      }
      const value = Number(item[column.property]);
      if (!Number.isNaN(value)) {
        valuesToSum.push(value);
      }
    });

    if (valuesToSum.length > 0) {
      sums[index] = `${valuesToSum.reduce((prev, curr) => prev + curr, 0)}`;
    } else {
      sums[index] = "";
    }
  });
  return sums;
};

const onSubmit = () => {
  if (purchaseForm.stockindetailList.length < 1) return ElMessage.error("请选择原料");
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      if (documentStatus.value === "edit") {
        await editStockin(purchaseForm).then(() => {
          router.push({
            path: "/procure/rejection",
            query: {
              upList: true
            }
          });
        });
      } else {
        await createStockin(purchaseForm).then(() => {
          router.push({
            path: "/procure/rejection",
            query: {
              upList: true
            }
          });
        });
      }
    } catch (error) {
      console.log(error);
    }
  });
};

const onCheckSubmit = async () => {
  if (purchaseForm.supplierId === "") return ElMessage.error("请选择供应商");
  if (purchaseForm.date === "") return ElMessage.error("请选择日期");
  if (purchaseForm.stockindetailList.length < 1) return ElMessage.error("请添加原料");
  await ruleFormRef.value.validate();
  await confirmStockin(purchaseForm);
  // console.log(res);
  ElMessage.success("审核成功");
  router.push({
    path: "/procure/rejection",
    query: {
      upList: true
    }
  });
};

const onChangeAmo = (index: number) => {
  purchaseForm.stockindetailList[index].amount = (
    purchaseForm.stockindetailList[index].price * purchaseForm.stockindetailList[index].quantity
  ).toFixed(2);
  // 计算基准单位
  purchaseForm.stockindetailList[index].unitBasis =
    purchaseForm.stockindetailList[index].convert * purchaseForm.stockindetailList[index].quantity;
};
const selectTreeTableRef = ref<InstanceType<typeof SelectTreeTable> | null>(null);
const openSelectTreeTable = (title: string, searchVal: string | number) => {
  const params = {
    title,
    isView: false,
    searchVal,
    index: 0,
    mate: "prodcutId",
    selTags: purchaseForm.stockindetailList
      .filter(age => age.goodsId !== 0)
      .map(i => {
        i.name = i.goodsName;
        i.id = i.productsId;
        return i;
      }),
    columns: [
      { type: "selection", width: 80 },
      { prop: "barcode", label: "编码", align: "left", width: 200 },
      { prop: "name", label: "原料名称", align: "left", minWidth: 220 },
      { prop: "productName", label: "规格", align: "left", minWidth: 100 },
      { prop: "unitName", label: "单位", align: "left", minWidth: 160 },
      { prop: "purPrice", label: "采购价格", minWidth: 120 }
      // { prop: "posPrice", label: "原料价格", minWidth: 120 }
    ],
    idName: "goodsCategoryId",
    treeApi: getWaresCategoryList,
    api: getWaresList
  };
  selectTreeTableRef.value?.acceptParams(params);
};
const supplierList = ref([]);
// const storeList = ref([]);
const { proxy } = getCurrentInstance(); // 支持访问内部组件实例， 只能在setup 或生命周期钩子
const refsInputName = ref("");

const handleKeyup = (event: any, index: number, cellIndex: number, isGift: boolean) => {
  if (cellIndex < 4 && !isGift) {
    refsInputName.value = "input" + String(index) + String(cellIndex + 1);
  } else if (cellIndex === 1 && isGift) {
    refsInputName.value = "input" + String(index) + "4";
  } else if (cellIndex === 4 && isGift) {
    refsInputName.value = "input" + String(index) + "5";
  } else {
    refsInputName.value = "input" + String(index + 1) + "1";
  }
  if (proxy.$refs[refsInputName.value]) {
    nextTick(() => {
      event.target.blur();
      proxy.$refs[refsInputName.value].focus();
    });
  }
};

const getYMD = () => {
  let myDate = new Date();
  let myYear = myDate.getFullYear(); // 获取完整的年份(4位,1970-????)
  let myMonth = myDate.getMonth() + 1; // 获取当前月份(0-11,0代表1月)
  let myToday = myDate.getDate(); // 获取当前日(1-31)
  myMonth = myMonth > 9 ? myMonth : "0" + myMonth;
  myToday = myToday > 9 ? myToday : "0" + myToday;
  let nowDate = myYear + "-" + myMonth + "-" + myToday;

  return nowDate;
};

onMounted(async () => {
  purchaseForm.mobile = userInfo.phone;
  purchaseForm.contacts = userInfo.userName;
  purchaseForm.date = getYMD();
  try {
    const [supplier] = await Promise.all([
      getSupplierList()
      // getStoreList()
      // useSelectStore().getDic("DiscountType")
    ]);
    supplierList.value = supplier.data.list;
    // storeList.value = store.data.list;
    if (route.query.id) {
      getStockin({ id: route.query.id }).then(res => {
        // 判断checkFlag状态，为true时就是已审核，已审核状态就是只需要查看信息，不能修改
        if (res.data.checkFlag) {
          documentStatus.value = "audited";
        } else {
          documentStatus.value = "edit";
        }
        Object.keys(purchaseForm).forEach(key => {
          if (res.data.hasOwnProperty(key)) {
            purchaseForm[key] = res.data[key];
          }
        });
      });
    } else {
      // purchaseForm.storeId = store.data.list[0].id;
      purchaseForm.supplierId = supplier.data.list[0].id;
      purchaseForm.supplierName = supplier.data.list[0].name;
    }
  } catch (error) {
    // 错误处理逻辑
    console.error("An error occurred:", error);
  }
  getHouseList();
});

// 获取仓库数据
const houserList = ref<any[]>([]);
const defaultHouserId = ref("");
const getHouseList = async () => {
  const { data } = await getStorehouseList({ pageNum: 1, pageSize: 9999 });
  houserList.value = data.list;
  houserList.value.forEach(v => {
    if (v.isDefault) {
      defaultHouserId.value = v.id;
    }
  });
};
</script>

<style lang="scss" scoped></style>
